package managedbean;

import entity.Employee;
import entity.Invoice;
import entity.Job;
import entity.Quotation;
import entity.Receipt;
import java.io.File;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.PhaseEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import session.stateless.EmployeeSessionBeanLocal;

@ManagedBean(name = "reportManagerBean")
@ViewScoped
public class ReportManagerBean {

    @Resource(name = "merlionerp_db")
    private DataSource merlionerp_db;
    @EJB
    private EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private String userId;
    private String userId2;
    private String department;
    private String industry;
    private String status;
    private String type;
    private String name;
    private String jobType;
    private String custId;
    private String roleType;
    private String company;
    private String quoteID;
    private Connection con;
    private ServletOutputStream outputStream;
    private String loadReport;
    private String yr;
    private String password;

    public ReportManagerBean() {
    }

    public void initView(PhaseEvent event) {
    }

    public void getWelcome(ActionEvent event) {
        Employee employee = (Employee) getUserSessionManagerBean().getSelectedItem();

        String url = "/Controller?action=exportMyEventsToPDF;userId=" + employee.getUserId();
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            context.getExternalContext().dispatch(url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            context.responseComplete();
        }
    }

// <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the department
     */
    public String getDepartment() {
        return department;
    }

    /**
     * @param department the department to set
     */
    public void setDepartment(String department) {
        this.department = department;
    }

// </editor-fold>
    //Page methods
    public void getFullReport(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        try {
            FacesContext context;
            context = FacesContext.getCurrentInstance();
            HttpServletResponse response;
            response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream readStream;
            readStream = context.getExternalContext().
                    getResourceAsStream("/Jasper_reports/" + file);


            response.setContentType("application/pdf");
            outputStream = response.getOutputStream();

            HashMap parameters = new HashMap();
            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");


            Class.forName("com.mysql.jdbc.Driver");



            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

            JasperRunManager.runReportToPdfStream(readStream,
                    outputStream, parameters, con);



        } catch (Exception ex) {
            System.out.println("ERROR HERE: " + ex.toString());
        } finally {

            con.close();
            outputStream.flush();
            outputStream.close();
        }
    }

    public void getFullReportByYear(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        try {
            FacesContext context;
            context = FacesContext.getCurrentInstance();
            HttpServletResponse response;
            response = (HttpServletResponse) context.getExternalContext().getResponse();
            InputStream readStream;
            readStream = context.getExternalContext().
                    getResourceAsStream("/Jasper_reports/" + file);


            response.setContentType("application/pdf");
            outputStream = response.getOutputStream();

            HashMap parameters = new HashMap();
            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");
            parameters.put("year", yr);

            Class.forName("com.mysql.jdbc.Driver");



            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

            JasperRunManager.runReportToPdfStream(readStream,
                    outputStream, parameters, con);



        } catch (Exception ex) {
            System.out.println("ERROR HERE: " + ex.toString());
        } finally {
            System.out.println("CLOSING...");
            con.close();
            outputStream.flush();
            outputStream.close();
        }
    }

    public void getReports(ActionEvent actionEvent) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        try {
            String file;

            if (actionEvent.getComponent().getId().equals("FullEmployee")) {
                file = "FullEmployeeReport.jasper";

                getFullReport(file);


            } else if (actionEvent.getComponent().getId().equals("CustomerIndustryType")) {

                file = "CustomerReportIndustryType.jasper";

                getFullReport(file);
            } else if (actionEvent.getComponent().getId().equals("CreditLimit")) {

                file = "creditLimitCountReport.jasper";

                getFullReport(file);
            } else if (actionEvent.getComponent().getId().equals("Outstanding")) {

                file = "OutstandingPayment.jasper";

                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("ProductReport")) {
                file = "ProductReport.jasper";

                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("ProductionBatchReport")) {
                file = "ProductionBatchReport.jasper";

                getFullReport(file);




            } else if (actionEvent.getComponent().getId().equals("SalesPerformance")) {
                file = "SalesPerformanceReportRevenue.jasper";
                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("EmployeeWelcome")) {
                file = "EmployeeWelcome2.jasper";
                getWelcomeByEmployeeID(file);


            } else if (actionEvent.getComponent().getId().equals("SalesPerformanceByProduct")) {
                file = "SalesPerformanceReport.jasper";
                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("FinanceReport")) {
                file = "FinanceReportFinal.jasper";
                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("DebtorReport")) {
                file = "DebtorsReport.jasper";

                getFullReport(file);

            } else if (actionEvent.getComponent().getId().equals("InquiryConversion")) {
                file = "InquiryConversionReport.jasper";

                getFullReportByYear(file);
            } else if (actionEvent.getComponent().getId().equals("JobFrequency")) {
                file = "JobReport.jasper";

                getFullReportByYear(file);
            } else if (actionEvent.getComponent().getId().equals("JobType")) {
                file = "JobReportJobType.jasper";

                getFullReport(file);


            } else if (actionEvent.getComponent().getId().equals("SalesOrder")) {
                file = "SalesOrderReport.jasper";
                getFullReportByYear(file);
            } else if (actionEvent.getComponent().getId().equals("ShippingReport")) {
                file = "ShippingOrderReportFinal.jasper";
                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("SalesPerformanceReportRevenueByMonth")) {
                file = "SalesPerformanceReportRevenueByMonth.jasper";

                getFullReportByYear(file);
            } else if (actionEvent.getComponent().getId().equals("SalesPerformanceReportRevenueByYear")) {
                file = "SalesPerformanceReportRevenueByYear.jasper";

                getFullReport(file);
            } else if (actionEvent.getComponent().getId().equals("SalesPerformanceExecutive")) {
                file = "SalesPerformanceExecutive_Final.jasper";

                getFullReportByYear(file);

            } else if (actionEvent.getComponent().getId().equals("Invoice")) {
                file = "invoice1.jasper";

                getReportByInvoiceID(file);

            } else if (actionEvent.getComponent().getId().equals("Receipt")) {
                file = "receipt3.jasper";

                getReportByReceiptID(file);
            } else if (actionEvent.getComponent().getId().equals("CustomerQuotation")) {
                file = "QuotationReport.jasper";

                getReportByCustID(file);

            } else if (actionEvent.getComponent().getId().equals("TurnOver")) {
                file = "InventoryTurnOver.jasper";

                   getFullReportByYear(file);
        
                  } else if (actionEvent.getComponent().getId().equals("RawMaterial")) {
                file = "InventoryRawMaterialReport.jasper";

                getFullReport(file);
            }



        } catch (Exception ex) {
            System.out.println("ERROR HERE: " + ex.toString());
            ex.printStackTrace();
        }



    }

    public void getReportByCustID(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        System.out.println("userSessionManagerBean.getSelectedInvoice(): " + ((Quotation) getUserSessionManagerBean().getSelectedItem()).getId());
        FacesContext context;
        context = FacesContext.getCurrentInstance();
        HttpServletResponse response;
        response = (HttpServletResponse) context.getExternalContext().getResponse();
        InputStream readStream;
        readStream = context.getExternalContext().
                getResourceAsStream("/Jasper_reports/" + file);

        ServletOutputStream outputStream;
        outputStream = response.getOutputStream();

        HashMap parameters = new HashMap();
        parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");
        //parameters.put("customer_ID", ((Job) userSessionManagerBean.getSelectedItem()).getCustomer().getCustId());
        // parameters.put("Quotation_ID", userSessionManagerBean.getSelectedQuotation().getId());
        // parameters.put("Quotation_ID", ( userSessionManagerBean.getSelectedItem()).getId());
        //parameters.put("Quotation_ID", (userSessionManagerBean.getSelectedItem()).getId());
  parameters.put("Quotation_ID", ((Quotation) getUserSessionManagerBean().getSelectedItem()).getId());

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

        JasperRunManager.runReportToPdfStream(readStream,
                outputStream, parameters, con);

        con.close();
        response.setContentType("application/pdf");
        outputStream.flush();
        outputStream.close();
    }

    public void getReportByReceiptID(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        System.out.println("userSessionManagerBean.getUserId(): " + getUserSessionManagerBean().getUserId());
        FacesContext context;
        context = FacesContext.getCurrentInstance();
        HttpServletResponse response;
        response = (HttpServletResponse) context.getExternalContext().getResponse();
        InputStream readStream;
        readStream = context.getExternalContext().
                getResourceAsStream("/Jasper_reports/" + file);

        ServletOutputStream outputStream;
        outputStream = response.getOutputStream();

        HashMap parameters = new HashMap();
        parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");

        parameters.put("ReceiptID", ((Receipt) getUserSessionManagerBean().getSelectedItem()).getId());

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

        JasperRunManager.runReportToPdfStream(readStream,
                outputStream, parameters, con);

        con.close();
        response.setContentType("application/pdf");
        outputStream.flush();
        outputStream.close();
    }

    public void getReportByInvoiceID(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {
        System.out.println("userSessionManagerBean.getUserId(): " + getUserSessionManagerBean().getUserId());
        FacesContext context;
        context = FacesContext.getCurrentInstance();
        HttpServletResponse response;
        response = (HttpServletResponse) context.getExternalContext().getResponse();
        InputStream readStream;
        readStream = context.getExternalContext().
                getResourceAsStream("/Jasper_reports/" + file);

        ServletOutputStream outputStream;
        outputStream = response.getOutputStream();
        System.out.println("userSessionManagerBean.getSelectedInvoice(): " + ((Invoice) getUserSessionManagerBean().getSelectedItem()).getId());
        HashMap parameters = new HashMap();
        parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");

        parameters.put("InvoiceID", ((Invoice) getUserSessionManagerBean().getSelectedItem()).getId());

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

        JasperRunManager.runReportToPdfStream(readStream,
                outputStream, parameters, con);

        con.close();
        response.setContentType("application/pdf");
        outputStream.flush();
        outputStream.close();
    }

    public void getWelcomeByEmployeeID(String file) throws IOException, ClassNotFoundException, SQLException,
            JRException {

        FacesContext context;
        context = FacesContext.getCurrentInstance();
        HttpServletResponse response;
        response = (HttpServletResponse) context.getExternalContext().getResponse();
        InputStream readStream;
        readStream = context.getExternalContext().
                getResourceAsStream("/Jasper_reports/" + file);

        ServletOutputStream outputStream;
        outputStream = response.getOutputStream();

        HashMap parameters = new HashMap();
        parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");
        parameters.put("employee_ID", ((Employee) getUserSessionManagerBean().getSelectedItem()).getUserId());
        String pwd = getEmployeeSessionBeanLocal().getPassword(((Employee) getUserSessionManagerBean().getSelectedItem()).getUserId());

        parameters.put("pw", pwd);
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/merlionerp_db?user=root&password=adminadmin");

        JasperRunManager.runReportToPdfStream(readStream,
                outputStream, parameters, con);

        con.close();
        response.setContentType("application/pdf");
        outputStream.flush();
        outputStream.close();
    }

    /**
     * @return the merlionerp_db
     */
    /**
     * @return the industry
     */
    public String getIndustry() {
        return industry;
    }

    /**
     * @param industry the industry to set
     */
    public void setIndustry(String industry) {
        this.industry = industry;
    }

    /**
     * @return the status
     */
    public String getStatus() {

        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the jobType
     */
    public String getJobType() {
        return jobType;
    }

    /**
     * @param jobType the jobType to set
     */
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }

    /**
     * @return the custId
     */
    public String getCustId() {
        return custId;
    }

    /**
     * @param custId the custId to set
     */
    public void setCustId(String custId) {
        this.custId = custId;
    }

    /**
     * @return the merlionerp_db
     */
    public DataSource getMerlionerp_db() {
        return merlionerp_db;
    }

    /**
     * @param merlionerp_db the merlionerp_db to set
     */
    public void setMerlionerp_db(DataSource merlionerp_db) {
        this.merlionerp_db = merlionerp_db;
    }

    /**
     * @return the roleType
     */
    public String getRoleType() {
        return roleType;
    }

    /**
     * @param roleType the roleType to set
     */
    public void setRoleType(String roleType) {
        this.roleType = roleType;
    }

    /**
     * @return the company
     */
    public String getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(String company) {
        this.company = company;
    }

    /**
     * @return the userId2
     */
    public String getUserId2() {
        return userId2;
    }

    /**
     * @param userId2 the userId2 to set
     */
    public void setUserId2(String userId2) {
        this.userId2 = userId2;
    }

    /**
     * @return the quoteID
     */
    public String getQuoteID() {
        return quoteID;
    }

    /**
     * @param quoteID the quoteID to set
     */
    public void setQuoteID(String quoteID) {
        this.quoteID = quoteID;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the loadReport
     */
    public String getLoadReport() {
        return loadReport;
    }

    /**
     * @param loadReport the loadReport to set
     */
    public void setLoadReport(String loadReport) {
        this.loadReport = loadReport;
    }

    /**
     * @return the employeeSessionBeanLocal
     */
    public EmployeeSessionBeanLocal getEmployeeSessionBeanLocal() {
        return employeeSessionBeanLocal;
    }

    /**
     * @param employeeSessionBeanLocal the employeeSessionBeanLocal to set
     */
    public void setEmployeeSessionBeanLocal(EmployeeSessionBeanLocal employeeSessionBeanLocal) {
        this.employeeSessionBeanLocal = employeeSessionBeanLocal;
    }

    /**
     * @return the yr
     */
    public String getYr() {
        return yr;
    }

    /**
     * @param yr the yr to set
     */
    public void setYr(String yr) {
        this.yr = yr;
    }
    /**
     * @return the employeeID
     */
}
